package com.example.service;

import com.example.entity.Booking;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通知服务，处理系统内部实时通知
 */
@Service
public class NotificationService {
    
    @Resource
    private ApplicationEventPublisher eventPublisher;
    
    // 缓存最近的预订通知
    private static final ConcurrentHashMap<String, Object> notificationCache = new ConcurrentHashMap<>();
    
    /**
     * 发送预订创建通知
     */
    public void sendBookingCreatedNotification(Booking booking) {
        Map<String, Object> eventData = new HashMap<>();
        eventData.put("type", "BOOKING_CREATED");
        eventData.put("booking", booking);
        eventData.put("timestamp", System.currentTimeMillis());
        
        // 缓存通知
        notificationCache.put("latest_booking", booking);
        
        // 发布事件
        eventPublisher.publishEvent(eventData);
    }
    
    /**
     * 发送预订状态变更通知
     */
    public void sendBookingStatusChangedNotification(Booking booking) {
        Map<String, Object> eventData = new HashMap<>();
        eventData.put("type", "BOOKING_STATUS_CHANGED");
        eventData.put("booking", booking);
        eventData.put("timestamp", System.currentTimeMillis());
        
        // 更新缓存通知
        notificationCache.put("latest_booking_update", booking);
        
        // 发布事件
        eventPublisher.publishEvent(eventData);
    }
    
    /**
     * 异步处理预订事件
     */
    @Async
    @EventListener
    public void handleBookingEvent(Map<String, Object> eventData) {
        String type = (String) eventData.get("type");
        Booking booking = (Booking) eventData.get("booking");
        
        // 这里可以添加WebSocket推送或其他实时通知逻辑
        System.out.println("处理预订事件: " + type + ", 预订ID: " + booking.getId());
    }
    
    /**
     * 获取最新预订通知
     */
    public Booking getLatestBookingNotification() {
        return (Booking) notificationCache.get("latest_booking");
    }
    
    /**
     * 获取最新预订更新通知
     */
    public Booking getLatestBookingUpdateNotification() {
        return (Booking) notificationCache.get("latest_booking_update");
    }
} 